<template>
    <div class="main-container">
        <div class="form-box" v-loading='loading'>
            <el-form :model="dataForm" :rules="rules" ref="dataForm" label-width="100px" class="form" label-position='right'>
                <span class="title">广告名称与备注</span>
                <el-row :gutter="41" class="item">
                  <el-col :span="10">
                    <el-form-item label="广告名称" prop="advertName" :rules="rules.advertName">
                        <el-popover
                        placement="top-start"
                        trigger="focus" 
                        content="长度在20个字符以内。">
                            <el-input v-model="dataForm.advertName" slot="reference" :maxlength="20"></el-input>
                        </el-popover>
                    </el-form-item>
                  </el-col>
                  <el-col :span="10">
                    <el-form-item label="备注" label-width="50px" prop="remark" :rules="rules.remark">
                        <el-popover
                        placement="top-start"
                        trigger="focus" 
                        content="长度在20个字符以内。">
                            <el-input v-model="dataForm.remark" slot="reference" :maxlength="20"></el-input>
                        </el-popover>
                    </el-form-item>
                  </el-col>
                </el-row>
                <span class="title title-adv">广告图片 <i>(支持 JPG PNG GIF 格式，200K以内的图片！)</i></span>
                <el-row :gutter="41" class="item item-img">
                  <el-col :span="10">
                    <div class="describe"><font color='red'>* </font>广告图片(750 * 240)</div>
                    <el-form-item label="" label-width="0">
                        <imgUpload  @onSuccess="btnAdvImg" @remove="removeAdvImg" :file-list-show.sync='AdvImg' :file-list.sync='imgPicList' :imgSize='0.1953125'>
                            <div class="el-upload-new el-upload-picture-new">
                            <div class="up-container el-upload">
                                <i class="el-icon-plus"></i>
                            </div>
                            </div>
                        </imgUpload>
                    </el-form-item>
                  </el-col>
                </el-row>
                <span class="title title-adv">广告链接与自定义内容</span>
                <el-row :gutter="41" class="item item-img">
                    <el-col :span="21">
                        <el-radio-group v-model="dataForm.advertOrCustom">
                            <el-radio class="radio" label="0">广告链接</el-radio>
                            <el-radio class="radio" label="1">自定义内容</el-radio>
                        </el-radio-group>
                        <div class="box">
                            <div v-if="dataForm.advertOrCustom === '0'">
                                <el-form-item label="" label-width="0" prop="linkUrl" :rules="rules.linkUrl">
                                    <el-popover placement="top-start" trigger="focus" content="请输入http://或https://前缀链接">
                                        <el-input slot="reference" v-model="dataForm.linkUrl" placeholder="请输入链接" style="width:46%"></el-input>
                                    </el-popover>
                                </el-form-item>
                            </div>
                            <div v-if="dataForm.advertOrCustom === '1'">
                                <Tinymce :height="360" :id="tinymceId" ref="dataForm.htmlSourceCode" v-model="dataForm.htmlSourceCode"></Tinymce>
                            </div>
                        </div>
                    </el-col>
                </el-row>
                <span class="title title-adv">投放区域</span>
                <el-row :gutter="41" class="item">
                    <el-col :span="10">
                        <el-form-item label-width="61px" label="省份" prop="provinceId" :rules="rules.provinceId">
                            <province v-model="dataForm.provinceId" @change="provinceChange"></province>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="41" class="item">
                    <el-col :span="10" v-if="agentTypeState=='2' || agentTypeState=='3'">
                        <el-form-item label-width="61px" label="城市" prop="cityId" :rules="rules.cityId">
                            <city v-model="dataForm.cityId" :province="dataForm.provinceId" ></city>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="41" class="item">
                    <el-col :span="10" v-if="agentTypeState=='3'">
                        <el-form-item label-width="61px" label="区县" prop="areaId" :rules="rules.areaId">
                            <region v-model="dataForm.areaId" :city="dataForm.cityId"></region>
                        </el-form-item>
                    </el-col>
                </el-row>
                <template  v-if="agentTypeState=='1'">
                    <el-row :gutter="41" class="item">
                        <el-col :span="10">
                            <el-form-item label-width="61px" label="城市">
                                <city v-model="dataForm.cityId" :province="dataForm.provinceId" ></city>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="41" class="item">
                        <el-col :span="10">
                            <el-form-item label-width="61px" label="区县">
                                <region v-model="dataForm.areaId" :city="dataForm.cityId"></region>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </template>
                <template  v-if="agentTypeState=='2'">
                    <el-row :gutter="41" class="item">
                        <el-col :span="10">
                            <el-form-item label-width="61px" label="区县">
                                <region v-model="dataForm.areaId" :city="dataForm.cityId"></region>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </template>
                <div class="man-bom"></div>
                <el-row :gutter="41" type="flex" justify="center" class="footer">
                    <el-col :span="2"><el-button @click="resetForm('dataForm')">取消</el-button></el-col>
                    <el-col :span="2"><el-button type="primary" :disabled="!this.dataForm.imgPic" @click="submitForm('dataForm')">保存</el-button></el-col>
                </el-row>
                <div class="man-bom"></div>
            </el-form>
        </div>
    </div>
</template>

<script>
    import { isEmpty } from 'utils/validate';
    import imgUpload from 'components/Upload/fileUpload';
    import Tinymce from 'components/Tinymce';
    import province from 'components/AdvArea/province';
    import city from 'components/AdvArea/city';
    import region from 'components/AdvArea/region';
    import { saveAdvert, listOrgRegionMapInfo } from 'api/advMangement';
    import { mapGetters } from 'vuex';

    export default {
        components: { imgUpload, Tinymce, province, city, region},
        data() {
            const validateEmpty = (rule, value, callback) => {
                if (!isEmpty(value) && value) {
                    callback(new Error('内容中不能存在空格'));
                } else {
                    callback();
                }
            };
            return {
                tinymceId: 'tinymceId',
                userTypeList: [],
                agentTypeState: '1',
                AdvImg: true,
                loading: false,
                imgPicList: [],
                dataForm: {
                    advertName: '',
                    remark: '',
                    imgPic: '',
                    advertOrCustom: '0',
                    linkUrl: '',
                    htmlSourceCode: '',
                    provinceId: '',
                    cityId: '',
                    areaId: ''
                },
                rules: {
                    advertName: [
                        { required: true, message: '内容不能为空', trigger: 'blur' },
                        { required: true, trigger: 'blur', validator: validateEmpty },
                        { min: 1, max: 20, message: '长度在20个字符以内', trigger: 'blur' }
                    ],
                    remark: [
                        { validator: validateEmpty },
                        { min: 1, max: 20, message: '长度在20个字符以内', trigger: 'blur' }
                    ],
                    linkUrl: [
                        { pattern: /^(https?):\/\/\w*\.\w*/, message: '请填完整的广告链接，广告链接需以\'http://\'或者\'https://\'开头' }
                    ],
                    provinceId: [
                        { required: true, message: '请选择省份', trigger: 'blur' }
                    ],
                    cityId: [
                        { required: true, message: '请选择城市', trigger: 'blur' }
                    ],
                    areaId: [
                        { required: true, message: '请选择区县', trigger: 'blur' }
                    ]
                }
            };
        },
        computed: {
            ...mapGetters([
                'agentType'
            ])
        },
        created() {
            this.getAgentType();
        },
        methods: {
            getAgentType() {   
                listOrgRegionMapInfo().then(response => { 
                    this.userTypeList = response.data.content;
                    console.log(this.userTypeList)
                })
            },
            provinceChange(val) {
                let count = 0;
                this.userTypeList.some(item => {
                    if (item.fProvinceId == val) {
                        if (count == 0) {
                            this.agentTypeState = item.fAgentType; 
                        } else {
                            if (item.fAgentType == '1') {
                                this.agentTypeState = '1';
                            } else if (item.fAgentType == '2' && this.agentTypeState != '1') {
                                this.agentTypeState = '2';
                            } else if (item.fAgentType == '3' && this.agentTypeState != '1' && this.agentTypeState != '2') {
                                this.agentTypeState = '3';
                            }
                        }
                        count = count + 1;
                    }
                });
                
            },
            btnAdvImg(obj) {
                this.imgPicList = obj;
                
                // var image = new Image();
                // image.src = obj.imgUrl;
                // image.onload = function() {
                //     console.log(image.width);
                //     console.log(image.height);
                // }
                this.dataForm.imgPic = `${obj.imgUrl}?imageView2/2/w/750/h/240`;
            },
            removeAdvImg() {
                this.dataForm.imgPic = '';
            },
            resetForm(dataForm) {
                this.$refs[dataForm].resetFields();
                this.$router.go(-1);
            },
            submitForm(dataForm) {
                this.$refs[dataForm].validate(valid => {
                    if (valid) {

                        if (!this.dataForm.imgPic) {
                            this.$message('请上传图片');
                            return;
                        }

                        if (this.dataForm.advertOrCustom === '1' && window.tinymce.get('tinymceId').getContent({format: 'text'}).trim().length > 6000) {
                            this.$message.error('自定义内容字数过多');
                            return false;
                        }

                        this.$confirm('是否添加?', ' ', {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: ' '
                        }).then(() => {
                            let advertName = this.dataForm.advertName; // 广告名称
                            let advertType = '0'; // 广告类型
                            let remark = this.dataForm.remark; // 备注
                            let advertAppType = ''; // 指定位置
                            let showTime = ''; // 设置显示时间
                            let iosPicOne = ''; // ios图片 1242*2208
                            let iosPicTWO = ''; // ios图片 640*1136
                            let iosPicThree = ''; // ios图片 640*960
                            let androidPic = ''; // android图片 720*1280
                            let advertOrCustom = this.dataForm.advertOrCustom; // 广告展现形式 0:广告链接 1：自定义
                            let linkUrl = this.dataForm.linkUrl; // 如果是广告链接则填上链接地址
                            let htmlSourceCode = this.dataForm.htmlSourceCode; // 如果自定义广告则是富文本编辑器内部编辑的内容
                            let provinceId = this.dataForm.provinceId; // 代理商省ID
                            let cityId = this.dataForm.cityId; // 代理商市ID
                            let areaId = this.dataForm.areaId; // 代理商区ID
                            let imgPic = this.dataForm.imgPic;// 非APP全屏广告位时图片地址
                            this.loading = true;
                            saveAdvert(
                                advertName, // 广告名称
                                advertType, // 广告类型
                                remark, // 备注
                                advertAppType, // 指定位置
                                showTime, // 设置显示时间
                                iosPicOne, // ios图片 1242*2208
                                iosPicTWO, // ios图片 640*1136
                                iosPicThree, // ios图片 640*960
                                androidPic, // android图片 720*1280
                                advertOrCustom, // 广告展现形式 0:广告链接 1：自定义
                                linkUrl, // 如果是广告链接则填上链接地址
                                htmlSourceCode, // 如果自定义广告则是富文本编辑器内部编辑的内容
                                provinceId, // 代理商省ID
                                cityId, // 代理商市ID
                                areaId, // 代理商区ID
                                imgPic
                            ).then(response => {
                                this.loading = false;
                                if (response.data.status == 200) {
                                    this.$message.success(response.data.errorMsg);
                                    this.$refs[dataForm].resetFields();
                                    this.$router.go(-1);
                                    this.$store.dispatch('UpdateCache');
                                } else {
                                    this.$message.error(response.data.errorMsg);
                                }
                            }).catch(() => {
                                this.loading = false;
                            });
                        }).catch(() => {
                            this.$message({type: 'info', message: '已取消'});          
                        });
                    } else {
                        return false;
                    }
                });
            }
        }
    };
</script>

<style lang="scss" scoped>
    .man-bom{
    margin: 20px 0;
    }
    .box{
    margin: 20px 0
    }
    .title {
    position: relative;
    font-size: 14px;
    color: rgb(106, 85, 72);
    padding-left: 24px;
    margin: 30px 0;
    display: block;
    &::after {
        position: absolute;
        content: "";
        width: 4px;
        height: 14px;
        background: #ff5e2c;
        left: 0;
        top: 4px;
    }
    }
    .describe {
    font-size: 14px;
    color: #666;
    margin: 20px 0;
    }
    .item {
        padding-left: 2px;
    }
    .item-img {
        padding-left: 26px;
    }
    .title-adv {
        margin-top: 80px;
    }
    .footer {
        margin-top: 80px;
    }
</style>